<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import axios from "axios";
import router from "@/router/index.js";
import {userStore} from "@/store/index.js";

// 登录方式切换
const activeTab = ref('username')
const store = userStore()
const userItemStore = userStore()
userItemStore.user
userItemStore.loggedIn
// 表单数据
const loginForm = ref({
  username: '',    // 账号
  password: '',   // 密码
  key: '',    // 图形验证码
  phone: '',      // 手机号
  smsCode: '',
  code: '' //缓存中验证码用
})

// 验证码图片URL
const keyUrl = ref('')
// 短信按钮状态
const smsButtonText = ref('获取验证码')
const smsButtonDisabled = ref(false)

// 表单验证规则
const rules = {
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'}
  ],
  // password: [
  //   { required: true, message: '请输入密码', trigger: 'blur' },
  //   { min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'blur' }
  // ],
  key: [
    {required: true, message: '请输入验证码', trigger: 'blur'},
    {len: 4, message: '验证码长度为4位', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ]
}

// 获取图形验证码
const getkey = () => {
  axios.get("/user/code").then(res => {
    keyUrl.value = res.data.base64Img;
    loginForm.value.code = res.data.key;
  })
}

// 发送短信验证码
const sendSmsCode = () => {
  if (!loginForm.value.phone) {
    ElMessage.warning('请输入手机号')
    return
  }

  // 模拟发送短信验证码
  smsButtonDisabled.value = true
  let countdown = 60

  const timer = setInterval(() => {
    countdown--
    smsButtonText.value = `${countdown}秒后重新获取`

    if (countdown <= 0) {
      clearInterval(timer)
      smsButtonText.value = '获取验证码'
      smsButtonDisabled.value = false
    }
  }, 1000)
  axios.get(`/user/sendSms/${loginForm.value.phone}`).then(res => {
    ElMessage.success('验证码已发送');
  })

}
// const qiehuan = () =>{
//   let loginForm =
// }
// 账号密码登录
const handleAccountLogin = () => {
  console.log("账号密码登录:", loginForm.value)
  axios.post("/user/login", loginForm.value).then(res => {
    if (res.data != null) {
      ElMessage.success("登陆成功")
      //修改保存的用户信息
      userItemStore.setUser(res.data);
      userItemStore.setStatus(true);
      userItemStore.fetchPermissions(userItemStore.user.id);
      console.log("权限信息:",userItemStore.permissions);
      //console.log("修改用户信息:",userItemStore.user);
    }
    router.push('/MainLayout');
  }).catch(err=>{
    ElMessage.error(err.response.data);
  })
}

// 手机号登录
const handlePhoneLogin = () => {
  console.log("手机号登录:", loginForm.value)
  axios.post("/user/telLoogin", loginForm.value).then(res => {
        ElMessage.success("登陆成功")
        //修改保存的用户信息
        userItemStore.setUser(res.data);
        userItemStore.loggedIn = true;
        router.push('/MainLayout');
      }).catch(err=>{
    ElMessage.error(err.response.data);
  })
}

// 初始化获取验证码
onMounted(() => {
  getkey()
})
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <h1 class="login-title">蜗牛智慧餐厅</h1>
      <p class="login-subtitle">智慧餐饮 · 美味生活</p>

      <el-tabs v-model="activeTab" class="login-tabs">
        <!-- 账号密码登录 -->
        <el-tab-pane label="账号密码登录" name="username">
          <el-form
              :model="loginForm"
              :rules="rules"
              ref="usernameFormRef"
              class="login-form"
          >
            <el-form-item prop="username">
              <el-input
                  v-model="loginForm.username"
                  placeholder="请输入账号"
                  prefix-icon="User"
                  clearable
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  placeholder="请输入密码"
                  prefix-icon="Lock"
                  show-password
                  clearable
              />
            </el-form-item>

            <el-form-item prop="key">
              <div class="key-container">
                <el-input
                    v-model="loginForm.key"
                    placeholder="请输入验证码"
                    class="key-input"
                    maxlength="4"
                />
                <img
                    :src="keyUrl"
                    alt="验证码"
                    class="key-image"
                    @click="getkey"
                    title="点击刷新验证码"
                />
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  class="login-button"
                  @click="handleAccountLogin"
              >
                登 录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 手机号登录 -->
        <el-tab-pane @click="qiehuan" label="手机号登录" name="phone">
          <el-form
              :model="loginForm"
              :rules="rules"
              ref="phoneFormRef"
              class="login-form"
          >
            <el-form-item prop="phone">
              <el-input
                  v-model="loginForm.phone"
                  placeholder="请输入手机号"
                  prefix-icon="Iphone"
                  clearable
                  maxlength="11"
              />
            </el-form-item>

            <el-form-item prop="smsCode">
              <div class="sms-container">
                <el-input
                    v-model="loginForm.smsCode"
                    placeholder="请输入短信验证码"
                    class="sms-input"
                    maxlength="6"
                />
                <el-button
                    class="sms-button"
                    :disabled="smsButtonDisabled"
                    @click="sendSmsCode"
                >
                  {{ smsButtonText }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                  type="primary"
                  class="login-button"
                  @click="handlePhoneLogin"
              >
                登 录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div class="login-footer">
        <span>还没有账号？<a href="#">立即注册</a></span>
        <span><a href="#">忘记密码？</a></span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
}

.login-box {
  width: 420px;
  padding: 40px;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.login-title {
  margin-bottom: 8px;
  color: #ff6b6b;
  font-size: 28px;
  font-weight: bold;
}

.login-subtitle {
  margin-bottom: 30px;
  color: #ff8e53;
  font-size: 14px;
}

.login-tabs {
  margin-bottom: 20px;
}

.login-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 24px;
}

.login-tabs :deep(.el-tabs__active-bar) {
  background-color: #ff6b6b;
  height: 3px;
}

.login-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #e4e7ed;
}

.login-form {
  margin-top: 20px;
}

.key-container,
.sms-container {
  display: flex;
  gap: 10px;
}

.key-input,
.sms-input {
  flex: 1;
}

.key-image {
  width: 120px;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
}

.sms-button {
  width: 140px;
}

.login-button {
  width: 100%;
  height: 44px;
  margin-top: 10px;
  font-size: 16px;
  background: linear-gradient(to right, #ff6b6b, #ff8e53);
  border: none;
}

.login-button:hover {
  opacity: 0.9;
}

.login-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  font-size: 14px;
  color: #909399;
}

.login-footer a {
  color: #ff6b6b;
  text-decoration: none;
}

.login-footer a:hover {
  text-decoration: underline;
}
</style>